package com.mayn.action;

import javax.servlet.http.Cookie;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;




public class TaobaoCookieAction {
	
	private static final Logger LOG = LoggerFactory.getLogger(TaobaoCookieAction.class);
	

	public static String getNewCookie() {
		String cookie = "";
		String sql = "SELECT QL_COOKIE FROM qn_login WHERE 1=1 Order by QL_ID DESC limit 1";
		Record getNewDsrCookieRec = Db.findFirst(sql);
		if (getNewDsrCookieRec != null) {
			cookie = getNewDsrCookieRec.getStr("QL_COOKIE");
		}
		return cookie;
	}

	public static Boolean saveCookie(String cookie) {
		try {
			String sql = "UPDATE qn_login SET QL_COOKIE='" + cookie + "',QL_UPDATE_DATETIME=now() WHERE 1=1 Order by QL_ID DESC limit 1";
			Db.update(sql);
			return true;
		} catch (Exception e) {
			LOG.error(e.getMessage());
			return false;
		}
	}

	public static Boolean saveUserAndCookie(String userName, String userPass, String cookie) {
		try {
			String sql = "INSERT INTO `qn_login` (`QL_NAME`, `QL_PASS`, `QL_COOKIE`, `QL_STATUS`, `QL_DEL`, `QL_CREATE_DATETIME`)" + " VALUES (?,?,?,0,0,now())";
			Db.update(sql, userName, userPass, cookie);
			return true;
		} catch (Exception e) {
			LOG.error(e.getMessage());
			return false;
		}
	}

	public static Cookie[] getCookieByStr(String str) {
		String[] cookiestrs = str.split(";");
		Cookie[] cookies = new Cookie[cookiestrs.length];
		for (int i = 0; i < cookies.length; i++) {
			if (cookiestrs[i].contains("=")) {
				String[] onecookie = cookiestrs[i].trim().split("=");
				if (onecookie.length > 2) {
					String value = cookiestrs[i].substring(onecookie[0].length() + 2, cookiestrs[i].length());
					cookies[i] = new Cookie(onecookie[0].trim(), value.trim());
				} else {
					if (onecookie.length == 2) {
						cookies[i] = new Cookie(onecookie[0].trim(), onecookie[1].trim());
					} else {
						cookies[i] = new Cookie(onecookie[0].trim(), "");
					}
				}
			} else {
				cookies[i] = new Cookie(cookiestrs[i].trim(), "");
			}
		}
		return cookies;
	}

	public static String getCookieByName(Cookie[] cookies, String name) {
		String ret = "";
		for (int i = 0; i < cookies.length; i++) {
			if (cookies[i].getName().equals(name)) {
				return cookies[i].getValue();
			}
		}
		return ret;
	}

}
